package org.eggdo.apof.server;

import java.io.*; 
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import org.dom4j.*;
import org.dom4j.io.*;

public class XmlParser {
	
	private String title;
	private String link;
	private ArrayList<Item> items;


	public static void main(String[] args) throws FileNotFoundException, DocumentException {
		new XmlParser("http://api.fanfou.com/statuses/user_timeline.rss?id=abcx");
	}
	
	public XmlParser(String fileName) {
		Document doc = read(fileName);
		
//		System.out.println(doc.asXML());
//		File f = new File("xx");
//		System.out.println("+++++++++++++++++++++++++++++++++++++++");
//		System.out.println(f.getAbsoluteFile().getPath());
//		System.out.println("+++++++++++++++++++++++++++++++++++++++");
		
		title = doc.selectSingleNode("rss/channel/title").getText();
		
		List<Node> messages = doc.selectNodes("rss/channel/item"); 
		items = new ArrayList<Item>();
		for(Iterator<Node> iter=messages.iterator();iter.hasNext();)
		{
			Node nd =(Node) iter.next();
			Item ms = new Item(nd.valueOf("title"),nd.valueOf("description"),nd.valueOf("pubDate"),nd.valueOf("link"));
			items.add(ms);
		}

	}
	

	public Document read(String fileName)  {
		Document document = null;
		try {
			SAXReader reader = new SAXReader();
			
			URL url = new URL(fileName);
			URLConnection uc = url.openConnection();
			uc.connect();
			InputStream f =uc.getInputStream();
			System.out.println(f.toString());
			
			System.out.println("+++++++++++++++++++++++++++++++");
			document = reader.read(f);

		}catch(Exception e){
			e.printStackTrace();
		}
		
		return document;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getLink() {
		return link;
	}

	public void setLink(String link) {
		this.link = link;
	}

	public ArrayList<Item> getItems() {
		return items;
	}
	
	

}
